package com.cyzy.util;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

import static com.aliyun.teautil.Common.toJSONString;

/**
 * @author cuncun
 * @create 2025-05-20 上午9:38
 *
 * 阿里云短信服务-工具类
 */

@Component
public class AliyunSmsUtil {

    private static final Logger logger = LoggerFactory.getLogger(AliyunSmsUtil.class);

    @Autowired
    private AliyunSmsProperties smsProperties;

    public Client createClient() throws Exception {
        // 验证配置是否完整
        if (smsProperties == null || 
            smsProperties.getAccessKeyId() == null || 
            smsProperties.getAccessKeySecret() == null) {
            throw new IllegalStateException("阿里云短信配置不完整，请检查配置");
        }

        logger.info("创建阿里云短信客户端，配置：{}", smsProperties);
        
        Config config = new Config()
                .setAccessKeyId(smsProperties.getAccessKeyId())
                .setAccessKeySecret(smsProperties.getAccessKeySecret());
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    public boolean sendSms(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            throw new IllegalArgumentException("短信参数不能为空");
        }

        // 验证必要参数
        String phone = map.get("phone");
        String code = map.get("code");
        if (phone == null || code == null) {
            throw new IllegalArgumentException("手机号或验证码不能为空");
        }

        try {
            Client client = createClient();
            SendSmsRequest request = new SendSmsRequest()
                    .setPhoneNumbers(phone)
                    .setSignName(smsProperties.getSignName())
                    .setTemplateCode(smsProperties.getTemplateCode())
                    .setTemplateParam("{\"code\":\"" + code + "\"}");

            logger.info("发送短信请求：phone={}, signName={}, templateCode={}", 
                phone, smsProperties.getSignName(), smsProperties.getTemplateCode());

            SendSmsResponse response = client.sendSms(request);
            logger.info("短信发送结果：{}", toJSONString(response));

            // 根据实际返回判断是否成功
            return "OK".equals(response.getBody().getCode());
        } catch (Exception e) {
            logger.error("短信发送失败：", e);
            throw new RuntimeException("短信发送异常: " + e.getMessage(), e);
        }
    }
}
